<template>
  <view class="page custom-page">
    <custom-head gradient back title="批量添加信息"></custom-head>
    <view class="batchAddition">
      <custom-step :step='step' ></custom-step>
      
			<view class="content">
				<view v-if="step === 1" class="first_page">
					<view class="text">*支持如下格式文件：excel文件</view>
					<u-button class="button" type="primary" @click="handleFile">上传文件</u-button>
				</view>

				<view class="second_page" v-else-if="step === 2">
					<u-checkbox @change="checkboxChange" v-model="allSelect">全选({{totle}}/{{ studentsList.length }})</u-checkbox>
					<view class="line"></view>

					<view v-for="(item, index) in studentsList" >
						<view class="list_item">
							<u-checkbox v-model="item.checked"></u-checkbox>
							<view class="item_left" @click="handlePopup(item, index)">
								<image class="img" :src="item.avatar ? item.avatar : '../../static/img/avatar.png'" mode="widthFix" />
								<view class="item_center">
									<text class="name">{{ item.name }} <text class="num">(学号{{ item.student_number }})</text> </text>
									<view class="contact">{{ item.emergency_contact }}{{ item.emergency_contact_phone }}</view>
								</view>
							</view>

							<view class="item_right" @click="handlePopup(item, index)">
								<view class="status">{{ item.status }}</view>
								<view class="inter">积分：{{ item.integration }}</view>
							</view>
						</view>
						<view class="line"></view>
					</view>

					<view class="btn">
						<u-button class="cur" @click="stepBack" shape="circle">上一步</u-button>
						<u-button class="suc" type="primary" @click="handleSuc" shape="circle">完成</u-button>
					</view>

				</view>

				<view class="third_page" v-else-if="step === 3">
					<u-circle-progress active-color="#2979ff" :percent="percent">
						<view class="u-progress-content">
							<!-- <view class="u-progress-dot"></view> -->
							<text class='u-progress-info'>
								{{ percent === 100 ? '上传完成' : '上传中' }}
							</text>
						</view>
					</u-circle-progress>
				</view>
			</view>

    </view>

		<u-popup v-model="showPopup" mode="bottom" z-index="1">
			<view class="popup_content">
				<view class="touxiang-box flex col a-center j-c-c">
					<u-upload 
					 style="z-index: 99;"
						max-count="1"  
						width="150rpx" 
						height="150rpx"
						:file-list="fileList"
						:form-data="{ type: 'avatar' }"
						:header="{ Authorization: token }"
						:action="BASE_URL + '/file/upload'"
						@on-change="onSuccess"
						@on-remove="omRemove"
						>
						<view class="touxiang" slot="addBtn">
							<image src="../../static/img/avatar.png" mode="widthFix"></image>
						</view>
					</u-upload>
					<text>头像</text>
				</view>

				<view class="form">
					<u-form :model="form" ref="uForm" label-width="156">
						<u-form-item label="姓名">
							<u-input v-model="form.name" placeholder="请输入学生姓名（昵称)16个字符内" />
						</u-form-item>
						<u-form-item label="性别">
							<u-radio-group v-model="form.sex">
								<u-radio v-for="(item, index) in sexList" :key="index" :name="item.name">{{ item.name }}</u-radio>
							</u-radio-group>
						</u-form-item>
						<u-form-item label="学生状态">
							<u-radio-group v-model="form.status">
								<u-radio v-for="(item, index) in stateList" :key="index" :name="item.name">{{ item.name }}</u-radio>
							</u-radio-group>
						</u-form-item>
						<u-form-item label="学号">
							<u-input v-model="form.student_number" placeholder="请输入学号" />
						</u-form-item>
						<u-form-item label="初始积分">
							<u-input v-model="form.integration" placeholder="请输入初始积分" />
						</u-form-item>
						<u-form-item label="家长昵称">
							<u-input v-model="form.emergency_contact" placeholder="请输入家长（紧急联系人）昵称" />
						</u-form-item>
						<u-form-item label="联系电话">
							<u-input v-model="form.emergency_contact_phone" placeholder="请输入家长（紧急联系人）电话号码" />
						</u-form-item>
					</u-form>
					<view class="button submit" @click="submit">确定</view>
				</view>


			</view>
		</u-popup>
  </view>
</template>

<script>
import { BASE_URL } from '../../api/config'
import { getExcel, addStudent } from "../../api/modules/student";
export default {
  data() {
    return {
			step: 1, // 操作步骤
			BASE_URL,
			percent: 0, // 进度条
			action: 'http://www.example.com/upload',
			token: uni.getStorageSync('token'),
			static_uri: getApp().globalData.glb_list.config.static_uri, // 获取全局配置文件
			fileList: [],
			selectIndex: 0, // 默认选中第一条
			showPopup: false, // 弹出框
			allSelect: false, // 是否全选
			studentsList: [], // 导入的学生
			sexList: [
        {
          name: '男',
          value: '0'
        },
        {
          name: '女',
          value: '1'
        },
        {
          name: '保密',
          value: '2'
        }
      ],
      sexMap: {
        '男': 0,
        '女': 1,
        '保密': 2,
      },
      stateList: [
        {
          name: '学习',
          value: '0'
        },
        {
          name: '休学',
          value: '1'
        },
        {
          name: '停学',
          value: '2'
        }
      ],
      stateMap: {
        '学习': 0,
        '休学': 1,
        '停学': 2,
      },
      form: {
        name: '',
        sex: '', // 0: 男，1：女，2：保密
        status: '', // 0：学习，1：休学，2：停学
        student_number: '',
        integration: '',
        emergency_contact: '',
        emergency_contact_phone: '',
        avatar: '',
      },
		};
  },
	watch: {
		studentsList: {
			handler(newVal, oldVal) {
				if (newVal.every(i => i.checked) ) {
					this.allSelect = true
				} else {
					this.allSelect = false
				}
			},
			deep: true
		}
	},
	computed: {
		totle: function() {
			return this.studentsList.filter(i => i.checked).length
		}
	},
  methods: {
		handleSuc() { // 成功
			let selectItemList = this.studentsList.filter(i => i.checked).map(i => ({...i, avatar: i.avatar ? i.avatar.split('com')[1] : '', sex: this.sexMap[this.form.sex], status: this.stateMap[this.form?.status], sid: this.glbId }));

			this.dosomething(selectItemList).then(res => {
				this.step = 3;
				this.percent = (res.length / selectItemList.length) * 100
			})

			console.log('完成修改 选中的内容',  selectItemList)
		},
		dosomething(arr) {
			let successCount = 0, failCount = 0;
			return Promise.all(
					arr.map(i => {
							return this._addStudent(i)
								.then((res) => {
										successCount++;
										return Promise.resolve(successCount);
									}).catch((err) => {
										failCount++;
										// return Promise.reject(failCount);
								})
					})
			);

		},
		async _addStudent(data) {
			return await new Promise((resolve, reject) => {
				return addStudent(data).then(res => {
					const { code } = res || {}
					if (code === 201) {
						resolve(code)
					} else {
						reject('添加失败')
					}
				})
			})
		},
		stepBack() { // 上一步
			this.step = 1;
			this.stateList = [];
			this.fileList = [];
		},
		submit() {
			let data = {
				...this.form,
			}

			if (this.form.avatar) {
				data.avatar = this.form.avatar.indexOf('com') > 0 ? this.form.avatar : `${this.static_uri}${this.form.avatar}`
			}
			this.fileList = []
			
			this.studentsList[this.selectIndex] = data;
			this.showPopup = false;
		},
		omRemove(index) { // 移除照片
			if (index === 0) {
				this.fileList = []
				this.form.avatar = ''
			}
		},
		onSuccess(data) { // 上传照片
      const res = JSON.parse(data.data)
      if (res.code == 201) {
        this.form.avatar = res.data.path
      } else {
        this.$refs.uUpload.clear()
        this.$u.toast('上传失败')
      }
    },
		handlePopup(param, index) {
			console.log('弹出框', param, index)
			param.avatar && (this.fileList = [{url: param.avatar}])
			let data = {
				...param,
			}
			this.selectIndex = index
			this.form = param
			this.showPopup = true;
		},
		checkboxChange(e) {
			const { value } = e || {}
			this.studentsList = this.studentsList.map(i => ({...i, checked: value}))
		},
    handleFile() {
			let _this = this
			let token = this.token
			uni.chooseFile({
				count: 1,
				success: function (res) {
					console.log(JSON.stringify(res.tempFilePaths));

					uni.uploadFile({
						url: `${BASE_URL}/file/upload`,
						filePath: res.tempFilePaths[0],
						header: {
							Authorization:token,
						},
						name: 'file',
						formData: {
							'token': token || '',
						},
						success: res_ => {
							let res = JSON.parse(res_.data);
							const { code, data } = res || {};
							if (code === 201) {
								console.log('上传成功啦！~', res)
								getExcel(data.id).then(res => {
									const { code, data } = res || {}
									console.log('返回excel的信息', data)
									_this.studentsList = data.map(i => ({...i, checked: true,  status: '学习'}))
								})
								_this.step = 2;
							} else {
								uni.showToast({
									icon: 'none',
									mask: true,
									title: '上传失败',
								});
							}
						}
					});
				}
			});
    },
  },
  onReady() {},
};
</script>
<style scoped lang="scss">

.touxiang-box {
  padding: 40rpx 0;
  font-size: 30rpx;
}

.touxiang {
  width: 150rpx !important;
  height: 150rpx !important;
  margin: auto;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 25rpx;
}

.touxiang image {
  width: 100%;
  height: 100%;
}

.form {
  background-color: #fff;
  padding: 0px 45rpx;
  overflow: hidden;
}

.button {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  background-color: #2979ff;
  color: #fff;
  font-size: 32rpx;
  text-align: center;
  line-height: 88rpx;
}

.content {
	height: calc(100vh - 232rpx);
	width: 100%;
	background-color: #fff;

	.first_page {
		height: 100%;
		display: flex;
		flex-direction: column;
		/* justify-content: center; */
		align-items: center;
		.text {
			margin-top: 215rpx;
			margin-bottom: 55rpx;
			font-size: 24rpx;
			font-family: PingFang-SC, PingFang-SC;
			font-weight: 500;
			color: #898989;
		}
		.button {
			width: 686rpx;
			height: 88rpx;
			background: #2979FF;
			border-radius: 48rpx;
		}
	}

	.second_page {
		padding: 30rpx 29rpx 26rpx;
		background-color: #fff;
		padding-bottom: 150rpx;
		.line {
			border-bottom: 1rpx solid #C8C9CB;
			margin-top: 25rpx;
		}

		.list_item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-top: 28rpx;
			.item_left {
				display: flex;
				.item_center {
					display: flex;
					flex-direction: column;
					justify-content: center;
					.name {
						font-size: 32rpx;
						font-family: PingFang-SC, PingFang-SC;
						font-weight: bold;
						color: #303133;
					}
					.num {
						margin-left: 10rpx;
						font-size: 24rpx;
						font-family: PingFang-SC, PingFang-SC;
						font-weight: 500;
						color: #303133;
					}
					.contact {
						width: 260rpx;
						font-size: 24rpx;
						font-family: PingFang-SC, PingFang-SC;
						font-weight: 500;
						color: #303133;
						text-overflow:ellipsis;/*省略号 */
						white-space:nowrap;/*溢出时不换行 */
						overflow:hidden;/*溢出时隐藏 */
					}
				}
			}
			.img {
				width: 120rpx !important;
				height: 120rpx !important;
				border-radius: 50%;
				margin-right: 30rpx;
			}
			.item_right {
				.status {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 138rpx;
					height: 52rpx;
					border-radius: 29rpx;
					border: 1rpx solid #979797;
					font-size: 24rpx;
					font-family: PingFang-SC, PingFang-SC;
					font-weight: 500;
					color: #303133;
				}
				.inter {
					font-size: 24rpx;
					font-family: PingFang-SC, PingFang-SC;
					font-weight: 500;
					color: #2979FF;
				}
			}
		}

		.btn {
			display: flex;
			position: fixed;
			bottom: 0;
			background-color: #fff;
			.cur {
				width: 337rpx;
				height: 88rpx;
				border-radius: 48rpx;
				border: 1rpx solid #2979FF;
				color: #2979FF;
			}
			.suc {
				width: 376rpx;
				height: 88rpx;
				background: #2979FF;
				border-radius: 48rpx;
			}
		}
	}

	.third_page {
		display: flex;
		align-items: center;
		justify-content: center;
		padding-top: 100rpx;
	}

	.popup_content {

		.img {
			display: flex;
			flex-direction: column;
			width: 150rpx !important;
			height: 150rpx !important;
			/* border-radius: 50%; */
		}
	
	}
}
.button input {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 9;
  width: 100%;
  height: 100%;
  opacity: 0;
}
.batchAddition-body >>> .u-upload,
.batchAddition-body >>> .u-upload > view {
  width: 100%;
}
</style>
